<?php
/**
 * Created by PhpStorm.
 * User: gqc
 * Date: 2017/1/10
 * Time: 22:02
 */
namespace Api\Service\Amazon;
use Home\Service\CommonService;

class ShipToAddressService extends CommonService{
    protected $shipToAddressModel   = NULL;
    protected $accountSiteModel = NULL;

    public function __construct() {
        $this->shipToAddressModel     = D('Api/Amazon/ShipToAddress','Model');
        $this->accountSiteModel     = D('Api/Amazon/AccountSite','Model');
    }

    public function getOrInsertShipToAddress ($accountId, $options = array()) {
        $siteId = $this->accountSiteModel->getSiteIdByAccountId($accountId);
        return !empty($options) ?
            $this->shipToAddressModel->getOrInsertShipToAddress($siteId, $options) :
            $this->shipToAddressModel->formatAddress($this->shipToAddressModel->getShipToAddress($siteId));
    }

    /**
     * @param $accountId
     * @param $centerId
     * 排查某个站点下某个仓库唯一标示是否存在
     */
    public function checkSiteCenterId ($accountId, $centerId) {
        $siteId = $this->accountSiteModel->getSiteIdByAccountId($accountId, $centerId);
        return $this->shipToAddressModel->checkSiteCenterId($siteId, $centerId);
    }

    /**
     * @param int $shipToAddressId
     * @return mixed
     * 根据目的仓库地址ID或者直接获取整个数组
     */
    public function getShipToAddress ($shipToAddressId = 0) {
        return $this->shipToAddressModel->formatAddress($this->shipToAddressModel->getShipToAddressById($shipToAddressId));
    }
    public function getOrInsertShipToAddressForUs ($accountId, $address)
    {
        $siteId = $this->accountSiteModel->getSiteIdByAccountId($accountId);
        if(empty($address))
            return FALSE;
        $options = $this->formatAddressForUs($address);
        return !empty($options)?$this->shipToAddressModel->getOrInsertShipToAddress($siteId,$options):FALSE;
    }
    public function formatAddressForUs($address){
        $arr = explode('<br>',$address);
        preg_match_all("/(?:\()(.*)(?:\))/i",trim(end($arr)), $result);
        if(empty($result) || empty($result[1]))
            return false;

        $options['CenterId'] = $result[1][0];

        $countryCode = substr(trim(end($arr)),0,2);
        if($countryCode != 'US')
            return false;
        $options['CountryCode'] = $countryCode;
        $proCityArr = explode(',', $arr[count($arr) - 2]);

        if(empty($proCityArr))
            return false;

        $options['City'] = trim($proCityArr[0]);
        $proArr = explode(' ', trim($proCityArr[1]));

        if(empty($proArr))
            return false;

        $options['StateOrProvinceCode'] = trim($proArr[0]);
        $options['PostalCode'] = trim($proArr[1]);

        $options['Name'] = trim($arr[0]);
        $options['AddressLine1'] = trim($arr[1]);
        return $options;
    }

}